package com.anysoft.web;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.webkit.WebView;

import com.anysoft.MentorApplication;
import com.aspsine.multithreaddownload.DownloadInfo;
import com.aspsine.multithreaddownload.DownloadManager;
import com.blankj.utilcode.util.ToastUtils;
import com.anysoft.WebViewNetworkProtocol;
import com.anysoft.bean.AppInfo;
import com.anysoft.me.base.BaseWebViewActivity;
import com.anysoft.me.config.CommentConfig;
import com.anysoft.me.utils.PermissionManager;
import com.anysoft.service.DownloadFileHelper;
import com.anysoft.service.DownloadService;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.OpenFileTipDialog;
import com.anysoft.utils.Utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lty on 2017/12/4.
 * 投资者类型转化页面
 */

public class InvestChangeActivity extends BaseWebViewActivity implements PermissionManager.OnPermissionListener {
    private String investorType;
    private Map<String, AppInfo> mAppInfos = new HashMap<>();
    private int downloadPosition;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isShowTitleBar(true);
        title.setText("投资者类型转化");
        investorType = getIntent().getStringExtra("investorType");
        generateUrl("investorTypeConversion", HttpUtils.getCommonParams2StringByWeb(mActivity)
                + "&investorType=" + investorType + "&cusNo=" + getFundCustomerNo());
        if (CommonUtil.isNetWorkConnected(mActivity)) {
            setWebViewConfig(loadUrl);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        register();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        unRegister();
        super.onDestroy();
    }

    private  Map<String, String> urlMap = new HashMap<>();
    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        MentorLogger.Log(TAG, "url=" + url);
        String url_decode = null;
        try {
            url_decode = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] params = url_decode.split("\\?")[1].split("&");
        for (int i = 0; i < params.length; i++) {
            //System.out.println("params--" + params[i]);
            String key = params[i].split("=")[0];
            String value = "";
            try {
                value = params[i].split("=")[1];
            } catch (Exception exception) {
                MentorLogger.Log(TAG, "value为null");
            }
            urlMap.put(key, value);
        }
        if (url.contains(WebViewNetworkProtocol.GO_DOWNLOAD_ONE)) {
            //下载业务办理申请表(成为专业投资者)
            gotoDownLoadFile(0);
        } else if (url.contains(WebViewNetworkProtocol.GO_DOWNLOAD_TWO)) {
            //下载专业投资者测试
            gotoDownLoadFile(1);
        } else if (url.contains(WebViewNetworkProtocol.GO_DOWNLOAD_THREE)) {
            //下载业务办理申请表(成为普通投资者)
            gotoDownLoadFile(2);
        } else if (url.contains(WebViewNetworkProtocol.GO_CLICK_TRANSFORM)) {
            if ("1".equals(investorType)) {
                title.setText("降级");
            } else {
                title.setText("升级");
            }
        } else if (url.contains(WebViewNetworkProtocol.GO_CHANGE_TITLE)) {
            title.setText("投资者类型转化");
        } else {
            webview.loadUrl(url);
        }
    }

    private void gotoDownLoadFile(int position) {
        downloadPosition = position;
        if (PermissionManager.getInstance().checkPermissions(this,PermissionManager.PERMISSION_READ_WRITE)){
            startDownloadOrOpen(position);
        } else {
            PermissionManager.getInstance().requestPermissions(this, PermissionManager.REQUEST_READ_WRITEE,
                    PermissionManager.PERMISSION_READ_WRITE, this);
        }
    }

    @NonNull
    private String generateFilePath(String fileName) {
        return new StringBuilder(Environment.getExternalStorageDirectory().getAbsolutePath())
                .append(File.separator).append(CommentConfig.DOWNLOAD_DIR_NAME).append(File.separator)
                .append(fileName).toString();
    }

    private void startDownloadOrOpen(int position) {
        String fileUrl = urlMap.get("downloadUrl");
        String fileName = urlMap.get("fileName") + fileUrl.substring(fileUrl.lastIndexOf("."));
        String pathname = generateFilePath(fileName);
        File file = new File(pathname);
        if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
            OpenFileTipDialog.openFiles(pathname, this);
            return;
        }
        AppInfo appInfo = new AppInfo();
        appInfo.setUrl(fileUrl);
        appInfo.setName(fileName);
        mAppInfos.put(fileUrl, appInfo);
        DownloadInfo downloadInfo = DownloadManager.getInstance().getDownloadInfo(appInfo.getUrl());
        if (downloadInfo != null) {
            appInfo.setProgress(downloadInfo.getProgress());
            appInfo.setDownloadPerSize(Utils.getDownloadPerSize(downloadInfo.getFinished(), downloadInfo.getLength()));
            appInfo.setStatus(AppInfo.STATUS_PAUSED);
        }
        DownloadFileHelper.getInstence().downloadStart(position, appInfo);
    }

    @Override
    public void onPermissionSuccess() {
        startDownloadOrOpen(downloadPosition);
        ToastUtils.showShort("切换为后台下载啦");
    }

    @Override
    public void onPermissionFail() {
        ToastUtils.showShort("获取权限失败,请重试");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private DownloadReceiver mReceiver;

    private void register() {
        mReceiver = new DownloadReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CommentConfig.ACTION_DOWNLOAD_COMPLITE);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, intentFilter);
    }

    private void unRegister() {
        if (mReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
        }
    }

    class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null || !action.equals(CommentConfig.ACTION_DOWNLOAD_COMPLITE)) {
                return;
            }
            final int position = intent.getIntExtra(CommentConfig.EXTRA_POSITION, -1);
            final AppInfo tmpInfo = (AppInfo) intent.getSerializableExtra(CommentConfig.EXTRA_APP_INFO);
            if (tmpInfo == null || position == -1) {
                return;
            }
            final AppInfo appInfo = mAppInfos.get(tmpInfo.getUrl());
            final int status = tmpInfo.getStatus();
            switch (status) {
                case AppInfo.STATUS_CONNECTING:
                    appInfo.setStatus(AppInfo.STATUS_CONNECTING);
                    break;

                case AppInfo.STATUS_DOWNLOADING:
                    appInfo.setStatus(AppInfo.STATUS_DOWNLOADING);
                    appInfo.setProgress(tmpInfo.getProgress());
                    appInfo.setDownloadPerSize(tmpInfo.getDownloadPerSize());
                    break;
                case AppInfo.STATUS_COMPLETE: //下载完成
                    appInfo.setStatus(AppInfo.STATUS_COMPLETE);
                    appInfo.setProgress(tmpInfo.getProgress());
                    appInfo.setDownloadPerSize(tmpInfo.getDownloadPerSize());
                    DownloadService.destory(MentorApplication.context);
                    break;

                case AppInfo.STATUS_PAUSED: //暂停
                    appInfo.setStatus(AppInfo.STATUS_PAUSED);
                    DownloadService.intentPause(MentorApplication.context, appInfo.getUrl());
                    break;
                case AppInfo.STATUS_NOT_DOWNLOAD:
                    appInfo.setStatus(AppInfo.STATUS_NOT_DOWNLOAD);
                    appInfo.setProgress(tmpInfo.getProgress());
                    appInfo.setDownloadPerSize(tmpInfo.getDownloadPerSize());
                    break;
                case AppInfo.STATUS_DOWNLOAD_ERROR:
                    appInfo.setStatus(AppInfo.STATUS_DOWNLOAD_ERROR);
                    appInfo.setDownloadPerSize("");
                    ToastUtils.showShort("下载失败");
                    break;
            }
        }
    }

}
